#!/usr/bin/env node

/**
 * 参数： --release x.x.x
 *
 */

const options = require('minimist')(process.argv.slice(2));
const { exec } = require('child_process');

const param = options['_'];
const createDirForBundle = (version = '0.0.0') => {
    return `mkdir ./bundle/bundle.${version}`;

};

const throwError = (error) => {
  console.error(`Error: An error occurred when ${error}\n`);
};

const promptSuccess = (success) => {
    console.log(`Success: ${success}`);
};

const promptCommand = (command) => {
    console.log(`> ${command}`);
};

const bundleSource = (filepath, platform) => {
    return `react-native bundle --entry-file index.js --bundle-output ${filepath}/${platform}/index.${platform}.bundle --platform ${platform} --assets-dest ${filepath}/${platform} --dev false`
};

const start = async () => {
    const version = param[0] || '0.0.0';
    const filepath = `./bundle/bundle.${version}`;

    const createDirForBundleCommand = createDirForBundle(version);
    promptCommand(createDirForBundleCommand);

    await exec(createDirForBundleCommand, (error) => {
        const command = `create bundle directory --release ${version}`;
        if(error){
            throwError(command);
            throw error;
        }
        promptSuccess(command)
    });

    const androidIosCommand = `mkdir ${filepath}/android ${filepath}/ios`;
    promptCommand(androidIosCommand);

    await exec(androidIosCommand, (error) => {
        const command = `mkdir ${filepath}/android ${filepath}/ios --release ${version}`;
        if(error){
            throwError(command);
            throw error;
        }
        promptSuccess(command)
    });

    const bundleSourceAndroid = bundleSource(filepath, 'android');
    promptCommand(bundleSourceAndroid);

    await exec(bundleSourceAndroid, (error) => {
        const command = `bundle index.android.js  --release ${version}`;
        if(error){
            throwError(command);
            throw error;
        }
        promptSuccess(command)
    });

    const bundleSourceIos = bundleSource(filepath, 'ios');
    promptCommand(bundleSourceIos);

    await exec(bundleSourceIos, (error) => {
        const command = `bundle index.ios.js  --release ${version}`;
        if(error){
            throwError(command);
            throw error;
        }
        promptSuccess(command)
    });
};
try{
    start();
}catch (error){
    console.log(error);
}